<template>
  <div class="abnormal-monitor-config">
    <!-- 查询表单 -->
    <el-form class="demo-form-inline" ref="formRef" :model="queryForm" label-width="100px" size="small" inline>
      <el-form-item label="规则名称" prop="ruleName">
        <el-input v-model="queryForm.ruleName" placeholder="规则名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="监测条件" prop="detectionCondition">
        <el-select v-model="queryForm.detectionCondition" placeholder="请选择监测条件" clearable>
          <el-option label="条件A" value="conditionA"></el-option>
          <el-option label="条件B" value="conditionB"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fetchConfigs">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-refresh" @click="resetData">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="el-row">
      <el-button type="primary" icon="el-icon-plus" plain size="small" @click="addConfig">新增</el-button>
      <el-button type="danger" icon="el-icon-delete" plain size="small" @click="handleBatchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
    </div>

    <!-- 异常监测配置列表 -->
    <el-table
      :data="tableData"
      height="100%"
      style="width: 100%; "
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column prop="ruleName" label="规则名称"></el-table-column>
      <el-table-column prop="detectionCondition" label="监测条件">
        <template slot-scope="scope">
          {{ scope.row.detectionCondition === 'conditionA' ? '条件A' : '条件B'}}
        </template>
      </el-table-column>
      <el-table-column prop="threshold" label="阈值"></el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="viewConfig(scope.row)">详情</el-button>
          <el-button type="text" @click="editConfig(scope.row)">编辑</el-button>
          <el-button type="text" @click="deleteConfig(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      background
      style="text-align: right"
    ></el-pagination>

    <!-- 异常监测配置对话框 -->
    <el-dialog title="异常监测配置" :visible.sync="dialogVisible" width="40%">
      <el-form :model="configForm" :rules="rules" ref="configForm" label-width="120px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="configForm.ruleName"></el-input>
        </el-form-item>
        <el-form-item label="监测条件" prop="detectionCondition">
          <el-select v-model="configForm.detectionCondition" placeholder="请选择监测条件">
            <el-option label="条件A" value="conditionA"></el-option>
            <el-option label="条件B" value="conditionB"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阈值" prop="threshold">
          <el-input-number v-model="configForm.threshold" :min="1" :max="100"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm('configForm')">保 存</el-button>
      </span>
    </el-dialog>

    <!-- 配置详情对话框 -->
    <el-dialog title="配置详情" :visible.sync="detailVisible" width="40%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="ID">{{ selectedConfig.id }}</el-descriptions-item>
        <el-descriptions-item label="规则名称">{{ selectedConfig.ruleName }}</el-descriptions-item>
        <el-descriptions-item label="监测条件">{{ selectedConfig.detectionCondition === 'conditionA' ? '条件A' : '条件B' }}</el-descriptions-item>
        <el-descriptions-item label="阈值">{{ selectedConfig.threshold }}</el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "AbnormalMonitorConfig",
  data() {
    return {
      queryForm: {
        ruleName: "",
        detectionCondition: ""
      },
      totalTableData: [
        // 示例数据
        { id: 1, ruleName: '规则A', detectionCondition: 'conditionA', threshold: 50 },
        { id: 2, ruleName: '规则B', detectionCondition: 'conditionB', threshold: 75 }
      ],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      configForm: {
        id: null,
        ruleName: '',
        detectionCondition: '',
        threshold: null
      },
      rules: {
        ruleName: [
          { required: true, message: '请输入规则名称', trigger: 'blur' }
        ],
        detectionCondition: [
          { required: true, message: '请选择监测条件', trigger: 'change' }
        ],
        threshold: [
          { required: true, message: '请输入阈值', trigger: 'blur' }
        ]
      },
      selectedRows: [],
      loading: false,
      detailVisible: false,
      selectedConfig: {}
    };
  },
  methods: {
    fetchConfigs() {
      this.loading = true;
      setTimeout(() => {
        const { ruleName, detectionCondition } = this.queryForm;
        let filteredData = this.totalTableData;

        if (ruleName) {
          filteredData = filteredData.filter(item => item.ruleName.includes(ruleName));
        }

        if (detectionCondition) {
          filteredData = filteredData.filter(item => item.detectionCondition === detectionCondition);
        }

        this.total = filteredData.length;
        this.tableData = filteredData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
        this.loading = false;
      }, 1000);
    },
    resetData() {
      this.$refs.formRef.resetFields();
      this.fetchConfigs();
    },
    addConfig() {
      this.dialogVisible = true;
      this.configForm = {
        id: null,
        ruleName: '',
        detectionCondition: '',
        threshold: null
      };
    },
    viewConfig(row) {
      this.selectedConfig = row;
      this.detailVisible = true;
    },
    editConfig(row) {
      this.dialogVisible = true;
      this.configForm = { ...row };
    },
    deleteConfig(row) {
      this.$confirm('此操作将永久删除该异常监测配置信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.tableData.indexOf(row);
        if (index !== -1) {
          this.tableData.splice(index, 1);
        }
        this.totalTableData.splice(this.totalTableData.indexOf(row), 1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的异常监测配置信息!'
        });
        return;
      }
      this.$confirm('此操作将永久删除选中的异常监测配置信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData = this.tableData.filter(row => !this.selectedRows.includes(row));
        this.totalTableData = this.totalTableData.filter(row => !this.selectedRows.includes(row));
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchConfigs();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchConfigs();
    },
    closeDialog() {
      this.dialogVisible = false;
      this.resetForm('configForm');
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.configForm.id) {
            // 更新现有配置
            const index = this.totalTableData.findIndex(config => config.id === this.configForm.id);
            if (index !== -1) {
              this.$set(this.totalTableData, index, { ...this.configForm });
            }
            const index2 = this.tableData.findIndex(receiver => receiver.id === this.configForm.id);
            if (index2 !== -1) {
              this.$set(this.tableData, index2, { ...this.configForm });
            }
          } else {
            // 添加新配置
            const newId = Math.max(...this.totalTableData.map(config => config.id)) + 1;
            const newConfig = { ...this.configForm, id: newId };
            this.totalTableData.push(newConfig);
            this.tableData.unshift(newConfig);
          }
          this.closeDialog();
          this.$message({
            type: 'success',
            message: '保存成功!'
          });
        } else {
          console.log('表单验证失败!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.fetchConfigs();
  }
};
</script>

<style scoped lang="scss">
.abnormal-monitor-config {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;

  .el-row {
    margin-bottom: 20px;
  }

  .el-table {
    flex: 1;
    margin-bottom: 20px;
  }
}
</style>
